package com.example.harmonet.slice;

import com.example.harmonet.ResourceTable;
import com.example.harmonet.harmtorch.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.InnerEvent;
import ohos.global.icu.util.Measure;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import java.io.IOException;
import java.util.Scanner;



public class Classifier {
    private Preprocessing preprocessing;
    private Context context;
    private static final String MODEL_PATH = "entry/resources/rawfile/cnn_model.bin";
    private NN net = null;

    public Classifier(AbilitySlice slice) {
        this.context = slice.getContext();
    }

    public void init() {
        net = new NN(
                new Conv1d(9, 18, 2, 1, 1, true),
                new Relu(),
                new MaxPool1d(2, 2, 1),
                new Conv1d(18, 36, 2, 1, 1, true),
                new Relu(),
                new MaxPool1d(2, 2, 1),
                new Conv1d(36, 72, 2, 1, 1, true),
                new Relu(),
                new MaxPool1d(2, 2, 1),
                new Conv1d(72, 144, 2, 1, 1, true),
                new Relu(),
                new MaxPool1d(2, 2, 1),
                new Flatten(),
                new Linear(1440, 8),
                new Softmax(),
                new Argmax()
        );
        try {
            loadModelFile();
        } catch (IOException e) {
            // e.printStackTrace();
        }

        preprocessing = new Preprocessing();
    }

    public int getResult(Measurement accelMeasurements, Measurement gyroMeasurements) {
        HiLogLabel label = new HiLogLabel(ohos.hiviewdfx.HiLog.LOG_APP, 0x00201, "test");
        // HiLog.warn(label, "in the result");
        preprocessing.execute(accelMeasurements, gyroMeasurements);
        float[][][] data = preprocessing.getOutputMatrix();
        Tensor input = new Tensor(1, 9, 128);
        input.setTensor(data);
        Tensor output = net.inference(input);
        HiLog.warn(label, output.toString());
        return (int)output.tensor()[0];

    }

    // Mappatura del file in memoria
    private void loadModelFile() throws IOException {
        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(MODEL_PATH);
        try {
            Resource resource = rawFileEntry.openRawFile();
            net.readTorch(resource);
        } catch (Exception e) {
            // e.printStackTrace();
            System.exit(0);
        }
    }
}
